import { createSlice } from "@reduxjs/toolkit";
import type { RootState } from "../index";
import { RouteCacheModel } from "../model";
import { getMenuList } from "../thunks/appThunk.ts";
import { MenuModel } from "@/core/models/system.model.ts";
import { localStorage } from "@/utils/storage.ts";
import { Message } from "@arco-design/web-react";
import axios, { CancelTokenSource } from "axios";
import { objIsEmpty } from "@/utils/index.ts";

export interface ThemeModel {
  title?: string;
  rgb?: string;
  hex: string;
  key: string;
  colorList: string[];
  chartColorList: string[];
  preset?: boolean; //是否为预设主题 预设主题不可更改主题色
}

interface AppSliceState {
  /** 路由缓存 */
  routeCache: RouteCacheModel[];
  menuList: MenuModel[];
  globalLoading: boolean;
  requestList: Record<string, CancelTokenSource>;
  theme: ThemeModel | null;
  themeList: ThemeModel[];
  requestLoading: boolean; //接口首是否在请求中
}

const initialState: AppSliceState = {
  routeCache: [],
  menuList: [],
  globalLoading: false,
  requestLoading: false,
  requestList: {},
  theme: null,
  themeList: [
    {
      title: "ROBIN'S EGG BLUE",
      rgb: "0, 206, 201",
      hex: "#00cec9",
      key: "robin_egg_blue",
      colorList: [
        "rgb(232, 255, 251)",
        "rgb(179, 245, 235)",
        "rgb(129, 235, 223)",
        "rgb(82, 226, 214)",
        "rgb(39, 216, 207)",
        "rgb(0, 206, 201)",
        "rgb(0, 171, 174)",
        "rgb(0, 134, 141)",
        "rgb(0, 100, 109)",
        "rgb(0, 68, 77)",
      ],
      preset: true,
      chartColorList: ["#009DAE", "#71DFE7", "#C2FFF9", "#FFE652"],
    },
    {
      title: "GREEN DARNER TAIL",
      hex: "#74b9ff",
      key: "green_darner_tail",
      colorList: [
        "rgb(232, 247, 255)",
        "rgb(209, 238, 255)",
        "rgb(186, 227, 255)",
        "rgb(162, 215, 255)",
        "rgb(139, 201, 255)",
        "rgb(116, 185, 255)",
        "rgb(72, 136, 210)",
        "rgb(38, 93, 166)",
        "rgb(14, 57, 121)",
        "rgb(14, 57, 121)",
        "rgb(0, 28, 77)",
      ],
      chartColorList: ["#6482AD", "#7FA1C3", "#E2DAD6", "#F5EDED"],
      preset: true,
      rgb: "116, 185, 255",
    },
    {
      title: "PICO-8 PINK",
      key: "pico_8_pink",
      hex: "#fd79a8",
      rgb: "253, 121, 168",
      colorList: [
        "rgb(255, 232, 236)",
        "rgb(255, 210, 219)",
        "rgb(254, 187, 204)",
        "rgb(254, 165, 190)",
        "rgb(253, 143, 178)",
        "rgb(253, 121, 168)",
        "rgb(209, 75, 126)",
        "rgb(165, 39, 92)",
        "rgb(121, 14, 62)",
        "rgb(77, 0, 37)",
      ],
      preset: true,
      chartColorList: ["#EECAD5", "#F1D3CE", "#F6EACB", "#D1E9F6"],
    },
    {
      title: "PRUNUS AVIUM",
      hex: "#e84393",
      colorList: [
        "rgb(255, 232, 239)",
        "rgb(250, 197, 216)",
        "rgb(246, 163, 194)",
        "rgb(241, 130, 176)",
        "rgb(237, 98, 160)",
        "rgb(232, 67, 147)",
        "rgb(193, 42, 120)",
        "rgb(154, 22, 95)",
        "rgb(115, 8, 71)",
        "rgb(77, 0, 47)",
      ],
      rgb: "232, 67, 147",
      preset: true,
      chartColorList: ["#F27BBD", "#FF4191", "#FF70AB", "#E90074"],
      key: "prunus_avium",
    },
    {
      title: "ELECTRON BLUE",
      hex: "#0984e3",
      key: "electron_blue",
      colorList: [
        "rgb(232, 249, 255)",
        "rgb(184, 230, 249)",
        "rgb(137, 208, 244)",
        "rgb(92, 185, 238)",
        "rgb(50, 159, 233)",
        "rgb(9, 132, 227)",
        "rgb(6, 104, 189)",
        "rgb(3, 77, 152)",
        "rgb(1, 54, 114)",
        "rgb(0, 33, 77)",
      ],
      preset: true,
      chartColorList: ["#6EACDA", "#478CCF", "#3FA2F6", "#4158A6"],
      rgb: "9, 132, 227",
    },
    {
      title: "ORANGEVILLE",
      hex: "#e17055",
      key: "orangeville",
      colorList: [
        "rgb(255, 240, 232)",
        "rgb(249, 216, 200)",
        "rgb(243, 191, 169)",
        "rgb(237, 166, 140)",
        "rgb(231, 140, 112)",
        "rgb(225, 112, 85)",
        "rgb(188, 76, 53)",
        "rgb(151, 45, 28)",
        "rgb(114, 21, 11)",
        "rgb(77, 5, 0)",
      ],
      chartColorList: ["#FF9874", "#FFD3B6", "#FF8A8A", "#C5705D"],
      preset: true,
      rgb: "225, 112, 85",
    },
  ],
};

export const appSlice = createSlice({
  name: "app",
  initialState,
  reducers: {
    addRouteToCache(state, action) {
      // 避免添加相同的路由
      const idx = state.routeCache.findIndex(
        (r) => r.pathname === action.payload.pathname
      );
      if (idx < 0) state.routeCache.push(action.payload);
    },
    removeRouteFromCacheByIndex(state, action) {
      state.routeCache.splice(action.payload, 1);
    },
    removeLeftRouteFromCacheByIndex(state, action) {
      state.routeCache = state.routeCache.filter((r, index) => {
        return index >= action.payload || r.fixed;
      });
    },
    removeRightRouteFromCacheByIndex(state, action) {
      state.routeCache = state.routeCache.filter((r, index) => {
        return index <= action.payload || r.fixed;
      });
    },
    removeOtherRouteFromCacheByIndex(state, action) {
      state.routeCache = state.routeCache.filter((r, index) => {
        return index === action.payload || r.fixed;
      });
    },
    removAllRouteFromCache(state) {
      state.routeCache = state.routeCache.filter((r) => {
        return r.fixed;
      });
    },
    setTheme(state, action) {
      state.theme = action.payload;
    },
    updateThemeList(state, action) {
      const localTheme = localStorage.get("theme") as ThemeModel;
      const { index, data, type } = action.payload;

      if (index >= 0) {
        if (type === "update") {
          state.themeList[index] = data;
        } else if (type === "delete") {
          if (localTheme.key === data.key) {
            Message.warning("该主题正在使用中，无法删除！");
          } else {
            state.themeList.splice(index, 1);
          }
        }
      } else {
        state.themeList.push(data);
      }
    },
    updateRequestLoading(state, action) {
      state.requestLoading = action.payload;
    },
    clearFormRequestList(state, action) {
      console.log(state);
      if (action.payload.config) {
        setTimeout(() => {
          const { url, method } = action.payload.config;
          const key = `${url}&${method}`;
          delete state.requestList[key];
          if (objIsEmpty(state.requestList)) {
            state.requestLoading = false;
          }
        }, 200);
      }
      const prevState = { ...state };
      delete prevState.requestList[action.payload];
      if (objIsEmpty(prevState)) {
        state.requestLoading = false;
      }
    },
    updateRequestList(state, action) {
      const { url, method } = action.payload.config;
      const key = `${url}&${method}`;
      const cancelTokenSource = axios.CancelToken.source();
      action.payload.config.cancelToken = cancelTokenSource;
      if (state.requestList[key]) {
        return cancelTokenSource.cancel("重复请求已取消");
      } else {
        state.requestList[key] = cancelTokenSource;
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getMenuList.pending, (state) => {
        state.globalLoading = true;
      })
      .addCase(getMenuList.rejected, (state) => {
        state.globalLoading = false;
      })
      .addCase(getMenuList.fulfilled, (state, action) => {
        state.globalLoading = false;
        state.menuList = action.payload;
      });
  },
});
export const {
  addRouteToCache,
  removeRouteFromCacheByIndex,
  removeLeftRouteFromCacheByIndex,
  removeRightRouteFromCacheByIndex,
  removeOtherRouteFromCacheByIndex,
  removAllRouteFromCache,
  setTheme,
  updateThemeList,
  updateRequestLoading,
  updateRequestList,
  clearFormRequestList,
} = appSlice.actions;
export const routeCache = (state: RootState) => state.app.routeCache;
export const menuList = (state: RootState) => state.app.menuList;
export const theme = (state: RootState) => state.app.theme;
export const requestLoading = (state: RootState) => state.app.requestLoading;
export const requestList = (state: RootState) => state.app.requestList;

export default appSlice.reducer;
